﻿using System;
using System.Collections.Generic;
using System.Text;
using Antu.Business.AbstractClass;
using System.Data;
using System.Windows.Forms;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using Antu.Business.Business;

namespace Antu.Business.Inheritance
{
    /// <!--
    /// 功能描述  : 物业用户注册审批数据操作
    /// 创建人  : LinJian
    /// 创建时间: 2007-07-09
    /// -->
    public class PropertyRegisterDataOperation : AbstractDataOperation
    {
        /************** 物业企业资质申报流程说明 *******************
         * 首先在外网申请注册号，然后转入到内网审批，如果通过将
         * 获得一个企业编号。
         * 
         * 根据unitid登录三级暂定一年资质申报系统输入申报基本信
         * 息，如果通过就具备了三级暂定一年资质
         * 
         * 如果具备三级暂定一年资质，就可以申请三级资质，将申请
         * 信息转入到内网审批，如果通过则在数据回迁到外网的时候
         * 将企业资质修改为3级，然后修改申报痕迹（TEMP_QUALIFICATIONREPORT）
         * 为三级（reportgrade='三级'）。
         * 
         * 具备三级资质的企业每年需要进行三级年检，这个不需要跑
         * 内网审批，仅仅需要各个区县房产局在外网进行审批，其中
         * 审批时有个标志位是IsYearCheck=1，这个标志位在各个企业
         * 提交审批的时候就已经设定为1.
        ********************************************************/

        #region 外网导出为临时文件
        /// <summary>
        /// 外网导出为临时文件
        /// </summary>
        /// <returns></returns>
        public override DataSet WebToTempFile(string[] arrTables)
        {
            Database dbTemp = BasicOperate.CreateWebDataBase();
            DataSet dsReturn = new DataSet();

            string strSql = string.Empty;

            int maxValue = arrTables.Length;
            int curValue = 1;
            foreach (string strTable in arrTables)
            {
                Application.DoEvents();
                base.SetProgress(maxValue, curValue, "正在导出...当前表名：\"" + strTable + "\"");

                Application.DoEvents();
                strSql = string.Format(@"SELECT * FROM {0} W WHERE W.CAN_SYNC=1", strTable);

                DataSet dsSource = dbTemp.ExecuteDataSet(CommandType.Text, strSql);
                DataTable dtCopy = dsSource.Tables[0].Copy();

                if (dtCopy.Rows.Count > 0)//有数据才导出
                {
                    dtCopy.TableName = strTable;

                    //将取得的标志位重新设置值
                    this.ConvertDataCan_Dyn(ref dtCopy);
                    dsReturn.Tables.Add(dtCopy);

                    //更新状态位
                    strSql = string.Format(@"UPDATE {0} W SET W.CAN_SYNC=0", strTable);
                    dbTemp.ExecuteNonQuery(CommandType.Text, strSql);

                }
                curValue++;
            }
            return dsReturn;
        }
        //做一下特殊处理
        private void ConvertDataCan_Dyn(ref DataTable dt)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i]["CAN_SYNC"] = 0;
            }
        }
        #endregion

        #region 内网导出为临时文件
        /// <summary>
        /// 内网导出为临时文件
        /// </summary>
        /// <returns></returns>
        public override DataSet InsideToTempFile(string[] arrTables)
        {
            Database dbTemp = BasicOperate.CreateInsideDataBase();
            DataSet dsReturn = new DataSet();

            string strSql = string.Empty;

            int maxValue = arrTables.Length;
            int curValue = 1;
            foreach (string strTable in arrTables)
            {
                Application.DoEvents();
                base.SetProgress(maxValue, curValue, "正在导出...当前表名：\"" + strTable + "\"");

                Application.DoEvents();
                strSql = string.Format(@"SELECT * FROM {0} W WHERE W.CAN_SYNC=1", strTable);

                DataSet dsSource = dbTemp.ExecuteDataSet(CommandType.Text, strSql);
                DataTable dtCopy = dsSource.Tables[0].Copy();

                if (dtCopy.Rows.Count > 0)//有数据才导出
                {
                    dtCopy.TableName = strTable;

                    //将取得的标志位重新设置值
                    this.ConvertDataCan_Dyn(ref dtCopy);
                    dsReturn.Tables.Add(dtCopy);

                    //更新状态位
                    strSql = string.Format(@"UPDATE {0} W SET W.CAN_SYNC=0", strTable);
                    dbTemp.ExecuteNonQuery(CommandType.Text, strSql);

                }
                curValue++;
            }
            return dsReturn;
        }        
        #endregion

        #region 临时文件导入到外网
        /// <summary>
        /// 临时文件导入到外网
        /// </summary>
        /// <returns></returns>
        public override void TempFileToWeb(string[] arrTables, DataSet dsSource)
        {
            Database dbTemp = BasicOperate.CreateWebDataBase();
            DbConnection conTemp = dbTemp.CreateConnection();

            //获取需要导入对象的所有表名
            List<string> lstNeedImportTables = ClsOracleSystemOperation.GetAllTablesName();

            //更新数据
            foreach (string strTable in arrTables)
            {
                if (dsSource.Tables.Contains(strTable))  //源数据中包含该表才操作
                {
                    DataTable dtSource = dsSource.Tables[strTable];
                    string strTempTable = dtSource.TableName.ToUpper();

                    if (lstNeedImportTables.Contains(strTempTable))
                    {
                        conTemp.Open();
                        DbTransaction dbTrans = conTemp.BeginTransaction(); //开始事务

                        try
                        {
                            int maxValue = dtSource.Rows.Count;
                            int curValue = 1;

                            //行循环
                            foreach (DataRow drCopy in dtSource.Rows)
                            {
                                Application.DoEvents();
                                SetProgress(maxValue, curValue, "正在导入...当前表名：\"" + strTempTable + "\"  ID：" + drCopy["ID"].ToString());

                                string strKeyName = string.Empty;
                                string strKeyId = string.Empty;
                                if (drCopy.Table.Columns.Contains("ID"))
                                {
                                    strKeyName = "ID";
                                    strKeyId = drCopy["ID"].ToString();
                                }
                                else
                                {
                                    continue;
                                }

                                Application.DoEvents();

                                //求取指定的行
                                DataSet dsOneRow = ClsOracleSystemOperation.GetOneRowData(strTempTable, strKeyName, strKeyId);
                                DataTable dtTemp = dsOneRow.Tables[0];

                                //如果不存在就添加一行空的数据
                                if (dtTemp.Rows.Count == 0)
                                {
                                    dtTemp.Rows.Add(dtTemp.NewRow());
                                }
                                //只取第一行数据
                                DataRow drTemp = dtTemp.Rows[0];
                                drTemp = ClsFieldType.UpdateColumns(drTemp, drCopy);

                                if (drTemp.RowState != DataRowState.Unchanged)
                                {
                                    DbCommand insertCommand = GetInsertCommand(dbTemp, DatabaseEngineType.OracleClient, strTempTable);
                                    DbCommand updateCommand = GetUpdateCommand(dbTemp, DatabaseEngineType.OracleClient, strTempTable, strKeyName);
                                    dbTemp.UpdateDataSet(dsOneRow, strTempTable, insertCommand, updateCommand, null, dbTrans);
                                }
                                curValue++;
                            }
                            dbTrans.Commit();
                        }
                        catch
                        {
                            dbTrans.Rollback();
                            throw;
                        }
                        finally
                        {
                            conTemp.Close();
                        }
                    }
                }
            }
        } 
        #endregion

        #region 临时文件导入到内网
        /// <summary>
        /// 临时文件导入到内网
        /// </summary>
        /// <param name="arrTables"></param>
        /// <param name="dsSource"></param>
        public override void TempFileToInside(string[] arrTables, DataSet dsSource)
        {
            Database dbTemp = BasicOperate.CreateInsideDataBase();
            DbConnection conTemp = dbTemp.CreateConnection();

            //获取需要导入对象的所有表名
            List<string> lstNeedImportTables = ClsOracleSystemOperation.GetAllTablesName();

            //更新数据
            foreach (string strTable in arrTables)
            {
                if (dsSource.Tables.Contains(strTable))  //源数据中包含该表才操作
                {
                    DataTable dtSource = dsSource.Tables[strTable];
                    string strTempTable = dtSource.TableName.ToUpper();

                    if (lstNeedImportTables.Contains(strTempTable))
                    {
                        conTemp.Open();
                        DbTransaction dbTrans = conTemp.BeginTransaction(); //开始事务

                        try
                        {
                            int maxValue = dtSource.Rows.Count;
                            int curValue = 1;

                            //行循环
                            foreach (DataRow drCopy in dtSource.Rows)
                            {
                                Application.DoEvents();
                                SetProgress(maxValue, curValue, "正在导入...当前表名：\"" + strTempTable + "\"  ID：" + drCopy["ID"].ToString());

                                string strKeyName = string.Empty;
                                string strKeyId = string.Empty;
                                if (drCopy.Table.Columns.Contains("ID"))
                                {
                                    strKeyName = "ID";
                                    strKeyId = drCopy["ID"].ToString();
                                }
                                else
                                {
                                    continue;
                                }

                                Application.DoEvents();

                                //求取指定的行
                                DataSet dsOneRow = ClsOracleSystemOperation.GetOneRowData(strTempTable, strKeyName, strKeyId);
                                DataTable dtTemp = dsOneRow.Tables[0];

                                //如果不存在就添加一行空的数据
                                if (dtTemp.Rows.Count == 0)
                                {
                                    dtTemp.Rows.Add(dtTemp.NewRow());
                                }
                                //只取第一行数据
                                DataRow drTemp = dtTemp.Rows[0];

                                drTemp = ClsFieldType.UpdateColumns(drTemp, drCopy);

                                try
                                {
                                    if (drTemp.RowState != DataRowState.Unchanged)
                                    {
                                        DbCommand insertCommand = GetInsertCommand(dbTemp, DatabaseEngineType.OracleClient, strTempTable);
                                        DbCommand updateCommand = GetUpdateCommand(dbTemp, DatabaseEngineType.OracleClient, strTempTable, strKeyName);
                                        dbTemp.UpdateDataSet(dsOneRow, strTempTable, insertCommand, updateCommand, null, dbTrans);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //屏蔽掉此异常，目前暂时无法解决
                                    if (ex.Message.Trim() != "ORA-01461: 仅可以为插入 LONG 列的 LONG 值赋值")
                                    {
                                        throw ex;
                                    }
                                }

                                curValue++;
                            }
                            dbTrans.Commit();
                        }
                        catch
                        {
                            dbTrans.Rollback();
                            throw;
                        }
                        finally
                        {
                            conTemp.Close();
                        }
                    }
                }
            }
        }
        #endregion
    }
}
